package server;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

import util.UserList;
import util.userObject;


public class MastermindThread extends Thread{


	private Socket socket;
	private MastermindServerLogic logic;
	private ObjectInputStream input;
	private ObjectOutputStream output;
	private UserList users;



	public MastermindThread(Socket socket){
		super();
		this.socket = socket;
	}

	/*getters and setters*/
	public Socket getSocket(){
		return this.socket;
	}

	public void setSocket(Socket socket){
		this.socket = socket;
	}

	public void run(){
		System.out.println("Starting thread..");
		this.logic = new MastermindServerLogic(this.socket);
		try {
			users = new UserList();
			output = new ObjectOutputStream(socket.getOutputStream());
			input = new ObjectInputStream(socket.getInputStream());

			try {
				output.writeObject("PING");
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			userObject userInfo = null;
			try {
				userInfo = (userObject) input.readObject();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if(userInfo.getType().equals("REG")){
				users.writeUser(userInfo);
				output.writeBoolean(users.checkLogin(userInfo));
			} else if(userInfo.getType().equals("LOG")){
				users.checkLogin(userInfo);
				output.writeObject("LOGGEDIN");
				
			}
			boolean gameOver = false;
			// In game loop
			while(logic.getGuessCount() != 10 || gameOver){
				char[] answerArray = new char[6];
				String recievedAnswer = null;
				try {
					recievedAnswer = (String) input.readObject();
				} catch (ClassNotFoundException e) {
					e.printStackTrace();
				}
				answerArray = recievedAnswer.toCharArray();
				output.writeObject(logic.checkAnswer(answerArray));
				gameOver = logic.isGameOver();
			}
			
		} catch (IOException e) {
			System.out.println("Error starting thread.");
			e.printStackTrace();
			System.exit(-1);
		}


	}

}
